<?php

/**
 * 案件调解
 * @author HelloWorld
 * UTF-8
 */
class MediateController extends Controller_Base
{

    //案件调解
    public function IndexAction()
    {
        $request = $this->getRequest();
        $page = intval($request->getQuery('page', 1));
        $limit = intval($request->getQuery('limit', 10));
        $type = $request->getQuery('type', 'first_mediate');
        $search = $request->getQuery('search', '');
        $searchfield = $request->getQuery('searchfield', []);
        $page = $page ? $page : 1;
        $start = ($page - 1) * $limit;
        $where = $this->getWhere();
        array_push($where, "caseStatus = 'case_mediate' and sysStatus = 1");
        if ($type != 'all') {//办理状态
            array_push($where, "mediateStatus = '{$type}'");
        }
        if($search){
            if(is_numeric($search)){
                array_push($where,"id = {$search}");
            }else{
                $caseId = $this->getCaseIdByLitigantName($search);
                array_push($where,"id in ({$caseId})");
            }
        }
        foreach ($searchfield as $key => $val){
            if(!empty($val)) {
                if ((strpos($key, 'Time') !== false || strpos($key, 'Date') !== false) && $key !='repaymentDate') {
                    $arr = explode(" 到", $val);
                    $begin = strtotime($arr[0]);
                    $end = strtotime($arr[1]) + 86400;
                    array_push($where, "$key >= $begin AND $key < $end");
                } elseif (strpos($key, 'start') !== false && is_numeric($val)) {
                    array_push($where, str_replace('start', '', $key) . " >= {$val}");
                } elseif (strpos($key, 'end') !== false && is_numeric($val)) {
                    array_push($where, str_replace('end', '', $key) . " < {$val}");
                } elseif(in_array($key,['litigantName','cardId','telephone'])){
                    $caseId = $this->getCaseIdByLitigantName($val,$key);
                    array_push($where,"id in ({$caseId})");
                } elseif(is_array($val)){
                    $temp = "'".implode("','", $val)."'";
                    array_push($where,"$key in ({$temp})");
                } elseif($key == 'importRecordId'){
                    array_push($where,"$key in ({$val})");
                } else {
                    if (is_numeric($val)) {
                        array_push($where, "{$key} = {$val}");
                    } else {
                        array_push($where, "{$key} = '{$val}'");
                    }
                }
            }
        }
        $query['limit'] = $limit;
        $query['search'] = $search;
        $query['type'] = $type;
        $query['searchfield']=$searchfield;

        $seacher = array(
            'where' => $where,
            'limit' => $limit,
            'start' => $start,
            'order' => 'lastCallTime ASC , `cardId` ASC'
        );
        $cases = Module_Mediate_Case::getInstance()->getAllBySearch(array("*"), $seacher, true);
        $total = Module_Mediate_Case::getInstance()->getAllBySearch(array("count(*) as num"), array('where' => $where), true);
        $isOperator = SmartyAdapter::getTplVars('isOperator');
        if($isOperator || 1){
            $sort_key = "mediatefield_Cases_".$this->admin['id'];
            //$where_key = "mediatefield_Where_".$this->admin['id'];
            //$md5where = md5(json_encode($where));
            //$rediswhere = Lib_Redis_String::get($where_key);
            //if (!$rediswhere || $rediswhere != $md5where){
            //Lib_Redis_String::del($where_key);
            //Lib_Redis_String::set($where_key,$md5where);
            Lib_Redis_SortedSet::del($sort_key);
            $cases_id = Module_Mediate_Case::getInstance()->getAllBySearch(["id"], ['where'=>$where,'order' => 'lastCallTime ASC , `cardId` ASC','group'=>'cardId'], true);

            foreach($cases_id as $k=>$cid){
                Lib_Redis_SortedSet::zAdd($sort_key,$k+1,$cid['id']);
            }
            //}
        }
        $total = $total[0]['num'];
        $totalPage = ceil($total / $limit);
        //赋值调解部门
        $this ->getMediationOrgan();
        //赋值资产方
        $this ->getAssets();
        //赋值短信
        $this ->getSMSConf('mediate');

        $this->getMediator(1);

        $cacheField = Lib_Redis_Hash::hGet($this->admin['id'],'mediatefield');
        $myField = $cacheField ? json_decode($cacheField,true) : Module_Mediate_Case::$mediatefield;
        if(count($myField) != count(Module_Mediate_Case::$mediatefield)){
            $myField = Module_Mediate_Case::$mediatefield;
        }
        SmartyAdapter::assign('arrList', $cases);
        SmartyAdapter::assign('totalPage', $totalPage);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('query', $query);
        SmartyAdapter::assign('type', $type);
        SmartyAdapter::assign('mediatefield',$myField);
        SmartyAdapter::assign('customLabel', Module_Mediate_Case::$customLabel);
        SmartyAdapter::assign('customGrade', Module_Mediate_Case::$customGrade);
        SmartyAdapter::assign('mediateResult', Module_Mediate_Case::$mediateResult);
        SmartyAdapter::assign('repayStatus', Module_Mediate_Case::$repayStatusArr);
        SmartyAdapter::assign('page_query', http_build_query($query));
        SmartyAdapter::assign('fieldType', 'mediatefield');

    }
    //案件联系
    public function contactAction()
    {
        $request = $this->getRequest();
        $page = intval($request->getQuery('page', 1));
        $limit = intval($request->getQuery('limit', 10));
        $type = $request->getQuery('type', 'today_contact');
        $search = $request->getQuery('search', '');
        $searchfield = $request->getQuery('searchfield', []);
        $page = $page ? $page : 1;
        $start = ($page - 1) * $limit;
        $where = $this->getWhere();
        array_push($where, "sysStatus = 1");
        $time1 = strtotime("today");
        if ($type == 'today_contact') {
            $time2 = $time1+86400;
            array_push($where, "nextTime > {$time1} and nextTime < $time2");
        }else{
            array_push($where, "nextTime > 0 and nextTime < $time1");
        }
        if($search){
            if(is_numeric($search)){
                array_push($where,"id = {$search}");
            }else{
                $caseId = $this->getCaseIdByLitigantName($search);
                if($caseId){
                    array_push($where,"id in ({$caseId})");
                }
            }
        }
        foreach ($searchfield as $key => $val){
            if(!empty($val)) {
                if (strpos($key, 'Time') !== false || strpos($key, 'Date') !== false) {
                    $arr = explode(" 到", $val);
                    $begin = strtotime($arr[0]);
                    $end = strtotime($arr[1]) + 86400;
                    array_push($where, "$key >= $begin AND $key < $end");
                } elseif (strpos($key, 'start') !== false && is_numeric($val)) {
                    array_push($where, str_replace('start', '', $key) . " >= {$val}");
                } elseif (strpos($key, 'end') !== false && is_numeric($val)) {
                    array_push($where, str_replace('end', '', $key) . " < {$val}");
                } elseif(in_array($key,['litigantName','cardId','telephone'])){
                    $caseId = $this->getCaseIdByLitigantName($val,$key);
                    array_push($where,"id in ({$caseId})");
                } elseif(is_array($val)){
                    $temp = "'".implode("','", $val)."'";
                    array_push($where,"$key in ({$temp})");
                } elseif($key == 'importRecordId'){
                    array_push($where,"$key in ({$val})");
                }else {
                    if (is_numeric($val)) {
                        array_push($where, "{$key} = {$val}");
                    } else {
                        array_push($where, "{$key} = '{$val}'");
                    }
                }
            }
        }
        $query['limit'] = $limit;
        $query['search'] = $search;
        $query['type'] = $type;
        $query['searchfield']=$searchfield;

        $seacher = array(
            'where' => $where,
            'limit' => $limit,
            'start' => $start,
            'order' => 'nextTime ASC , `cardId` ASC'
        );
        $cases = Module_Mediate_Case::getInstance()->getAllBySearch(array("*"), $seacher, true);
        $total = Module_Mediate_Case::getInstance()->getAllBySearch(array("count(*) as num"), array('where' => $where), true);
        $isOperator = SmartyAdapter::getTplVars('isOperator');
        if($isOperator || 1){
            $sort_key = "contactfield_Cases_".$this->admin['id'];
//            $where_key = "contactfield_Where_".$this->admin['id'];
//            $md5where = md5(json_encode($where));
//            $rediswhere = Lib_Redis_String::get($where_key);
//            if (!$rediswhere || $rediswhere != $md5where){
//                Lib_Redis_String:: set($where_key,$md5where);
//                Lib_Redis_SortedSet::del($sort_key);
                $cases_id = Module_Mediate_Case::getInstance()->getAllBySearch(["id"], ['where'=>$where,'order' => 'nextTime ASC , `cardId` ASC','group'=>'cardId'], true);
                foreach($cases_id as $k=>$cid){
                    Lib_Redis_SortedSet::zAdd($sort_key,$k+1,$cid['id']);
                }
            //}
        }
        $total = $total[0]['num'];
        $totalPage = ceil($total / $limit);
        //赋值调解部门
        $this ->getMediationOrgan();
        //赋值资产方
        $this ->getAssets();
        $this ->getSMSConf('contact');
        $this->getMediator(1,1);

        $cacheField = Lib_Redis_Hash::hGet($this->admin['id'],'contactfield');
        $myField = $cacheField ? json_decode($cacheField,true) : Module_Mediate_Case::$contactfield;
        if(count($myField) != count(Module_Mediate_Case::$contactfield)){
            $myField = Module_Mediate_Case::$contactfield;
        }
        SmartyAdapter::assign('arrList',$cases);
        SmartyAdapter::assign('totalPage', $totalPage);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('query', $query);
        SmartyAdapter::assign('type', $type);
        SmartyAdapter::assign('mediatefield',$myField);
        SmartyAdapter::assign('customLabel', Module_Mediate_Case::$customLabel);
        SmartyAdapter::assign('customGrade', Module_Mediate_Case::$customGrade);
        SmartyAdapter::assign('mediateResult', Module_Mediate_Case::$mediateResult);
        SmartyAdapter::assign('repayStatus', Module_Mediate_Case::$repayStatusArr);
        SmartyAdapter::assign('page_query', http_build_query($query));
        SmartyAdapter::assign('fieldType', 'contactfield');
        SmartyAdapter::$templateName = 'mediate/index';

    }
    //案件还款
    public function returnedMoneyPlanAction(){
        $request = $this->getRequest();
        $page = intval($request->getQuery('page', 1));
        $limit = intval($request->getQuery('limit', 10));
        $type = $request->getQuery('type', 'first_mediate');
        $search = $request->getQuery('search', '');
        $searchfield = $request->getQuery('searchfield', []);
        $page = $page ? $page : 1;
        $start = ($page - 1) * $limit;
        $where = $this->getWhere();
        if ($type == 'today_plan') {
            $today = date("j");
            array_push($where, "repaymentDate = {$today} and status in ('no_repay','wait_repay','keep_repay')");
        }elseif($type == 'before_plan'){
            $today= strtotime("today");
            $list = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch(
                ["planId"],
                ['where'=>[
                    "repaymentDate < {$today}",
                    "status in ('keep_plan','reject_plan')",
                ]], true);
            if($list){
                $planId = implode(',',array_unique(array_column($list,'planId')));
                array_push($where, "id in ({$planId})");
                array_push($where, "status <> 'finish_repay'");
            }else{
                array_push($where, "id = 0");
            }

        }
        if($search){
            if(is_numeric($search)){
                array_push($where,"caseId = {$search}");
            }else{
                $caseId = $this->getCaseIdByLitigantName($search);
                array_push($where,"caseId in ({$caseId})");
            }
        }

        foreach ($searchfield as $key => $val){
            if(!empty($val)) {
                if ((strpos($key, 'Time') !== false || strpos($key, 'Date') !== false) && $key !='repaymentDate') {
                    $arr = explode(" 到", $val);
                    $begin = strtotime($arr[0]);
                    $end = strtotime($arr[1]) + 86400;
                    array_push($where, "$key >= $begin AND $key < $end");
                } elseif (strpos($key, 'start') !== false && is_numeric($val)) {
                    array_push($where, str_replace('start', '', $key) . " >= {$val}");
                } elseif (strpos($key, 'end') !== false && is_numeric($val)) {
                    array_push($where, str_replace('end', '', $key) . " < {$val}");
                } elseif(in_array($key,['litigantName','cardId','telephone'])){
                    $caseId = $this->getCaseIdByLitigantName($val,$key);
                    array_push($where,"caseId in ({$caseId})");
                } elseif(is_array($val)){
                    $temp = "'".implode("','", $val)."'";
                    array_push($where,"$key in ({$temp})");
                } elseif($key == 'importRecordId'){
                    array_push($where,"$key in ({$val})");
                }else {
                    if (is_numeric($val)) {
                        array_push($where, "{$key} = {$val}");
                    } else {
                        array_push($where, "{$key} = '{$val}'");
                    }
                }
            }
        }

        $query['limit'] = $limit;
        $query['search'] = $search;
        $query['type'] = $type;
        $query['searchfield']=$searchfield;
        $seacher = array(
            'where' => $where,
            'limit' => $limit,
            'start' => $start,
            'order' => 'repaymentDate ASC , `id` ASC'
        );


        $list = Module_Mediate_ReturnedMoneyPlan::getInstance()->getAllBySearch(array("*"), $seacher, true);
        $total = Module_Mediate_ReturnedMoneyPlan::getInstance()->getAllBySearch(array("count(*) as num"), array('where' => $where), true);
        $isOperator = SmartyAdapter::getTplVars('isOperator');
        if($isOperator){
            $sort_key = "planfield_Cases_".$this->admin['id'];
            $where_key = "planfield_Where_".$this->admin['id'];
            $md5where = md5(json_encode($where));
            $rediswhere = Lib_Redis_String::get($where_key);
            if (!$rediswhere || $rediswhere != $md5where){
                Lib_Redis_String:: set($where_key,$md5where);
                Lib_Redis_SortedSet::del($sort_key);
                $cases_id = Module_Mediate_ReturnedMoneyPlan::getInstance()->getAllBySearch(["caseId"], ['where'=>$where,'order' => 'repaymentDate ASC , `id` ASC'], true);
                foreach($cases_id as $k=>$cid){
                    Lib_Redis_SortedSet::zAdd($sort_key,$k+1,$cid['caseId']);
                }
            }
        }
        $total = $total[0]['num'];

        $totalPage = ceil($total / $limit);
        //复制调解组
        $this->getMediationOrgan();
        //赋值资产方
        $this->getMediator(1,1);

        $this ->getAssets();
        $this ->getSMSConf('replayPlan');
        $cacheField = Lib_Redis_Hash::hGet($this->admin['id'],'planfield');
        $myField = $cacheField ? json_decode($cacheField,true) : Module_Mediate_Case::$planfield;
        if(count($myField) != count(Module_Mediate_Case::$planfield)){
            $myField = Module_Mediate_Case::$planfield;
        }
        SmartyAdapter::assign('fieldType', 'planfield');
        SmartyAdapter::assign('mediatefield',$myField);
        SmartyAdapter::assign('type', $type);
        SmartyAdapter::assign('arrList',$list);
        SmartyAdapter::assign('totalPage', $totalPage);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('query', $query);
        SmartyAdapter::assign('type', $type);
        SmartyAdapter::assign('repayStatus', Module_Mediate_Case::$repayStatusArr);
        SmartyAdapter::assign('page_query', http_build_query($query));
        SmartyAdapter::$templateName = 'mediate/index';
    }

    //获取当前案件的下一个案件id
    public function getNextidAction(){
        $case_id = $this->_request->getPost('caseId',0);
        $direction = $this->_request->getPost('direction');
        $fieldType = $this->_request->getPost('fieldType');
        $sort_key = "{$fieldType}_Cases_".$this->admin['id'];
        $current_index = Lib_Redis_SortedSet::zScore($sort_key,$case_id);
        if($direction == 'prev'){
            $next_id = Lib_Redis_SortedSet::zRangeByScore($sort_key,$current_index-1,$current_index-1);
        }else{
            $next_id = Lib_Redis_SortedSet::zRangeByScore($sort_key,$current_index+1,$current_index+1);
        }
        if(empty($next_id['0'])){
            AjaxTool::returnJsonData(400,'没有啦！');

        }
        AjaxTool::returnJsonData(200,'',['caseId'=>$next_id['0']]);
    }

    //自定义列表展示顺序
    public function setListAction(){
        $checkField = $this->_request->getPost('checkField', []);
        $orderField = $this->_request->getPost('orderField', []);
        $fieldType = $this->_request->getPost('fieldType', '');
        if(empty($checkField) || empty($orderField) ||  empty($orderField)){
            AjaxTool::returnJsonData(4006);
        }
        if(!in_array($fieldType,['mediatefield'])){
            AjaxTool::returnJsonData(4005);
        }
        $confField =  Module_Mediate_Case::$$fieldType;
        $myField = [];
        foreach ($orderField as $field){
            $temp = $confField[$field];
            $temp['default'] = in_array($field,$checkField) ? 1 : 0;
            $myField[$field] = $temp;
        }
        Lib_Redis_Hash::hSet($this->admin['id'],$fieldType,json_encode($myField));
        AjaxTool::returnJsonData(200);
    }
    //标记失约用户
    public function markNoShowAction(){
        $request = $this->getRequest();
        $planId = $request->getPost('id', 0);
        if(empty($planId)){
            AjaxTool::returnJsonData(4005);
        }
        $plan = Module_Mediate_ReturnedMoneyPlan::getInstance()->getItemById($planId);
        if(empty($plan)){
            AjaxTool::returnJsonData(4005);
        }
        $res = Module_Mediate_ReturnedMoneyPlan::getInstance()->singleUpdate(
            [
                'id'=>$planId,
                "updateTime"=>time(),
                "status"=>'break_repay',
            ]
        );
        if(!$res){
            AjaxTool::returnJsonData(4000);
        }
        $res = Module_Mediate_Case::getInstance()->singleUpdate(
            [
                'id'=>$plan['caseId'],
                "updateTime"=>time(),
                "repayStatus"=>'Break_repay',
            ]
        );
        if(!$res){
            AjaxTool::returnJsonData(4000);
        }
        $data = [
            'caseId' => $plan['caseId'],
            'status' => 'replay_no_show',
            'operationUid' => $this->admin['id'],
            'operationName' => $this->admin['name'],
            'operationContent' =>"失约还款",
            'remark' => "标记为还款案件",
            'createTime' => time(),
        ];
        $post_data = [
            'type' => 'Module_Task_Case',
            'method' => 'addOperateLog',
            'data' => $data
        ];
        @Module_Queue_Base::addQueue($post_data);
        AjaxTool::returnJsonData(200,'操作成功');
    }
    //提交到审核
    public function submitAuditAction(){
        $request = $this->getRequest();
        $caseId = ($request->getPost('case_id', []));
        $closeReason = ($request->getPost('closeReason', 0));
        if(!$closeReason || !in_array($closeReason,[1,2,3,4])){
            AjaxTool::returnJsonData(4001);
        }
        if (empty($caseId)) {
            AjaxTool::returnJsonData(4001);
        }
        $saveData = [
            'caseStatus' => 'mediate_audit',
            'closeReason' => $closeReason,
            'updateTime' => time()
        ];
        $res = Module_Mediate_Case::getInstance()->saveByIds($saveData, $caseId);
        //修改成功，添加日志记录
        if($res){
            $id_arr = explode(',', $caseId);
            foreach ($id_arr as $id){
                $data = [
                    'caseId' => $id,
                    'status' => 'submit_mediate_audit',
                    'operationUid' => $this->admin['id'],
                    'operationName' => $this->admin['name'],
                    'operationContent' =>"提交调解审核",
                    'remark' => Module_Mediate_Case::$closeReason[$closeReason],
                    'createTime' => time(),
                ];
                $post_data = [
                    'type' => 'Module_Task_Case',
                    'method' => 'addOperateLog',
                    'data' => $data
                ];
                @Module_Queue_Base::addQueue($post_data);
            }

        }
        AjaxTool::returnJsonData(200, '提交成功' );
    }
    //发送短信
    public function sendSmsAction(){
        $request = $this->getRequest();
        //案件id
        $case_id = $request->getPost('case_id', '');
        $sms_code = $request->getPost('sms_code', '');
        $batch = $request->getPost('batch', 1);
        if (!$case_id) {
            AjaxTool::returnJsonData(4005);
        }
        if($batch == 1){
            $case_id_arr = explode(",", $case_id);
            foreach($case_id_arr as $id){
                $post_data = [
                    'type' => 'Module_Task_Sms',
                    'method' => 'send',
                    'data' => [
                        'caseId'=>$id,
                        'smsCode'=>$sms_code,
                        'operationUid'=>$this->admin['id'],
                        'operationName'=>$this->admin['name'],
                        'mediationOrganId'=>$this->admin['mediationOrganId'],
                    ],
                ];
                @Module_Queue_Base::addQueue($post_data);
            }
            AjaxTool::returnJsonData(200,"提交成功，正在异步发送");

        }else{
            $res = Module_Task_Sms::sendHandler([
                'caseId'=>$case_id,
                'smsCode'=>$sms_code,
                'operationUid'=>$this->admin['id'],
                'operationName'=>$this->admin['name'],
                'mediationOrganId'=>$this->admin['mediationOrganId'],
            ]);
            AjaxTool::returnJsonData($res['code'],$res['message']);
        }

    }




}
